<?php
session_start();
require_once __DIR__.'/../../utils/checkTokenUtils.php'; // 登录验证
require_once __DIR__.'/../../model/BorrowModel.php';
require_once __DIR__.'/../../model/BookModel.php';
use model\BorrowModel;

// 仅允许POST请求
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    $_SESSION['error_message'] = '错误：仅支持POST请求';
    header('Location: borrow.php');
    exit;
}

// 获取并验证表单数据
$userId = isset($_POST['user_id']) ? intval($_POST['user_id']) : 0;
$bookId = isset($_POST['book_id']) ? intval($_POST['book_id']) : 0;
$borrowTime = isset($_POST['borrow_time']) ? trim($_POST['borrow_time']) : '';

// 基础验证
if (!$userId || !$bookId || !$borrowTime) {
    $_SESSION['error_message'] = '错误：用户、图书和借阅时间为必填项';
    header('Location: borrow.php');
    exit;
}


// 检查用户是否存在（可选但推荐）
// 假设UserModel有getUserById方法，需引入并验证...

// 插入借阅记录
$borrowModel = new BorrowModel();
$insertResult = $borrowModel->addBorrowRecord($userId, $bookId, $borrowTime);

if ($insertResult !== false) {
    $_SESSION['success_message'] = '借阅记录添加成功！';
} else {
    $_SESSION['error_message'] = '错误：数据库插入失败';
}

header('Location: borrow.php');
exit;
